/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package post.dataaccess;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import post.Product;
import post.ProductCatalog;

/**
 *
 * @author Harry/Ayush
 */
public class ProductReader {           
    
    static int position=0;
    ProductCatalog catalog;
    String productFile;
    
    public ProductReader(String productFile) throws IOException {
        this.productFile = productFile;
        catalog = new ProductCatalog();
        try {
            
            FileReader fr = new FileReader(productFile);
            /*location of products.txt file will be passed as the arguement, pls change the location accordingly.*/
            
            BufferedReader br = new BufferedReader(fr);       
            int i=0;
            
            while(true)
                {
                    String s = br.readLine();   //Reads the file line by line
                    if(s==null)                 //comparison to determine end of file (null)
                    {
                        break;                    
                    }                    
                    String[] temp= new String[3];
                    temp=s.split(",");
                    catalog.add(temp[0], temp[1], Float.parseFloat(temp[2]));
                    i++;
                }
        } catch (Exception ex) {
            System.out.println( ex.getMessage( ) );
            Logger.getLogger(ProductReader.class.getName()).log(Level.SEVERE, null, ex);
        }
        
      
    }
    
    public void addProduct(Product product) throws FileNotFoundException, IOException {        
        String newProduct=new String();
        newProduct=product.getUpc()+","+product.getDescription()+","+Float.toString(product.getPrice())+"\n";
        FileWriter fw = new FileWriter(productFile,true);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(newProduct);
        bw.close();        
    }
    
    public ProductCatalog loadCatalog() {
        return catalog;
    }
}